/**
 * 媒体处理相关工具方法
 * @author: Ruan Jiazhen
 * @date: 2024-04-03 16:52:48
 **/

type ChooseAndCropImgOption = Partial<
  Pick<WechatMiniprogram.ChooseMediaOption, 'sizeType' | 'sourceType'> & Pick<WechatMiniprogram.CropImageOption, 'cropScale'>
>;

/**
 * 选择并裁剪图片，默认裁剪比例为1:1，返回裁剪后的图片临时路径
 * @param newOptions 选择图片和裁剪的配置
 */
export const chooseAndCropImg = async (options: ChooseAndCropImgOption = {}) => {
  const defaultOptions: Required<ChooseAndCropImgOption> = {
    sizeType: ['original', 'compressed'],
    sourceType: ['album', 'camera'],
    cropScale: '1:1',
  };

  const { sizeType, sourceType, cropScale } = { ...defaultOptions, ...options };

  const { tempFiles } = await wx.chooseMedia({
    count: 1,
    mediaType: ['image'],
    sizeType,
    sourceType,
  });

  const { tempFilePath } = tempFiles[0];

  const { tempFilePath: corpImgTemFilePath } = await new Promise<WechatMiniprogram.CropImageSuccessCallbackResult>((resolve) => {
    wx.cropImage({
      src: tempFilePath,
      cropScale,
      success(res) {
        resolve(res);
      },
    });
  });

  return corpImgTemFilePath;
};
